package com.cy.cy2025.service

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.icu.text.SimpleDateFormat
import android.os.Binder
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import com.cy.cy2025.databinding.ActivityTestServiceBinding
import com.cy.cy2025.service.LocalTestService.Listener
import com.cy.cy2025.util.LogUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class LocalTestService : LifecycleService() {


    companion object {
        const val TAG = "LocalTestService"
    }


    inner class TestBinder : Binder() {
        fun getService() = this@LocalTestService

        fun testMessage(msg: String) {
            LogUtil.i(TAG, "testLog:$msg")

        }
    }

    interface Listener {
        fun onListen(timeStr: String)
    }

    val listeners = mutableListOf<Listener>()

    fun addListener(listener: Listener) {
        if (listener in listeners) return
        listeners.add(listener)
    }

    fun removeListener(listener: Listener) {
        if (listener !in listeners) return
        listeners.remove(listener)
    }

    var testBinder: TestBinder? = null

    var timeStr = ""

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "onCreate")
        startTask()
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(TAG, "onDestroy")
    }

    override fun onBind(intent: Intent): IBinder {
        super.onBind(intent)
        Log.i(TAG, "onBind")
        if (testBinder == null) testBinder = TestBinder()
        return testBinder!!
    }

    override fun onRebind(intent: Intent?) {
        super.onRebind(intent)
        Log.i(TAG, "onRebind")
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.i(TAG, "onUnbind")
        return super.onUnbind(intent)
    }

    @SuppressLint("SimpleDateFormat")
    private fun startTask() {
        //模拟长期任务
        lifecycleScope.launch {
            while (true) {
                timeStr = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
                Log.i(TAG, "LocalTestService运行中：$timeStr")
                listeners.forEach {
                    it.onListen(timeStr)
                }
                delay(5000)
            }
        }
    }


}

class TestServiceActivity : AppCompatActivity() {

    val binding by lazy { ActivityTestServiceBinding.inflate(layoutInflater) }

    var service: LocalTestService? = null

    val listener: Listener = object : Listener {
        @SuppressLint("SetTextI18n")
        override fun onListen(timeStr: String) {
            binding.tv.text = "来自同进程service的信息：$timeStr"
        }
    }
    var serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(
            name: ComponentName?,
            binder: IBinder?
        ) {
            val mBinder = binder as LocalTestService.TestBinder
            service = mBinder.getService()
            service?.addListener(listener)
            mBinder.testMessage("activity发来的信息")
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            service = null
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        //startService(Intent(this, LocalTestService::class.java))
        bindService(Intent(this, LocalTestService::class.java), serviceConnection, BIND_AUTO_CREATE)


    }

    override fun onDestroy() {
        super.onDestroy()
        runCatching {
            service?.removeListener(listener)
            unbindService(serviceConnection)
            LogUtil.i("TestServiceActivity", "解绑服务")
        }.onFailure {
            LogUtil.i("TestServiceActivity", "解绑服务失败:${it.stackTraceToString()}")
        }
    }
}
